 package com.server;
 
import cn.com.messageManager.MessageManager;

import com.server.thread.ConnectionThread;
import com.server.thread.ThreadTask;

import java.nio.charset.Charset;

import java.util.Timer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
 public class PokeServerHandle extends IoHandlerAdapter
 {
	   boolean on_off = false;
	   private static Logger logger = LoggerFactory.getLogger(PokeServerHandle.class);
	 
	   /**
	    * 接受信息过滤
	    */
	   public void messageReceived(IoSession session, Object obj)
	     throws Exception
	   {
		     ConnectionThread thread = (ConnectionThread)session.getAttribute("thread");
		 
		     byte[] array = (byte[])obj;
		     String str = new String(array, Charset.forName("utf-8"));
		 
		     if (str.startsWith("<policy")) 
		     {
		       logger.info("请求安全策略...");	 
		    	 
		       String xml="<cross-domain-policy> " 
		       +"<allow-access-from domain=\"*\" to-ports=\"*\"/>" 
		       +"</cross-domain-policy> "+"\0"; 
		       
		       byte[] xmlarray = xml.getBytes(Charset.forName("utf-8"));
		       session.write(xmlarray);
		       return;
		     }
	 
		     try
		     {
		    	 if (thread != null)
		    		 thread.beging(array);
		     }
		     catch (Exception e) 
		     {
		    	 e.printStackTrace();
		    	 logger.error("messageReceived  throw error:{}", e.getMessage());
		     }
	   }
	 
	   /**
	    * 通道关闭
	    */
	   public void sessionClosed(IoSession session)
	     throws Exception
	   {   
		   doCloseOrTimer(session);
	   }
	 
	   /**
	    * 通道异常信息
	    */
	   public void exceptionCaught(IoSession session, Throwable cause)
	     throws Exception
	   {
	     doCloseOrTimer(session);
	   }
	 
	   /**
	    * 会话生成
	    */
	   public void sessionCreated(IoSession session)
	     throws Exception
	   {
	     ConnectionThread thread = new ConnectionThread(session);
	     session.setAttribute("thread", thread);
	   }
	 
	   /**
	    * 当发送消息成功时调用这个方法
	    */
	   public void messageSent(IoSession session, Object obj) throws Exception
	   {
	   }
	 /**
	  *这个方法在IoSession 的通道进入空闲状态时调用，对于UDP 协议来说，这个方法始终不会
	  * 被调用。
	  */
	   public void sessionIdle(IoSession session, IdleStatus statucs) throws Exception
	   {
	     ConnectionThread conn = null;
	     if ((ConnectionThread)session.getAttribute("thread") == null)
	     {
		       if (session.containsAttribute("ownset")) 
		       {
		         session.removeAttribute("ownset");
		       }
		       session.close(true);
		       return;
	     }
	     conn = (ConnectionThread)session.getAttribute("thread");
	 
	     if (!PokeServer.usermap.containsKey(String.valueOf(conn.getUser().getUser_id())))
	     {
		       session.removeAttribute("thread");
		       if (session.containsAttribute("ownset")) 
		       {
		         session.removeAttribute("ownset");
		       }
		       conn = null;
		       session.close(true);
		       return;
	     }
	 
	     MessageManager.sentLip(session);
	   }
	 
	   /**
	    * 断线后等待重连
	    * @param session
	    */
	   public void doCloseOrTimer(IoSession session)
	   {
	     ConnectionThread thread = null;
	     if (session.getAttribute("thread") == null) 
	     {
	    	 return;
	     }
	     thread = (ConnectionThread)session.getAttribute("thread");
	     if(thread==null)
	    	 return;
	    // int user_id=thread.getUser().getUser_id();
	     
	     logger.info("有人断连了");
	    // logger.info("等待重连");
	     session.removeAttribute("thread");
	     if (session.containsAttribute("ownseat")) 
	     {
	    	 session.removeAttribute("ownseat");
	     }
	     session.close(true);
	     thread.setSession(null);
	     if (PokeServer.threadmap.containsValue(thread))
	     {
	    	 return;
	     }
	 
	     try
	     {
		       if (thread.getUser() == null) 
		       {
		    	   logger.info("找不到此人");
		    	   thread.dispose();
		    	   return;
		       }
		       PokeServer.threadmap.put(Integer.valueOf(thread.getUser().getUser_id()), thread);
	     } catch (Exception e) 
	     {
		       e.printStackTrace();
		       logger.error(" doCloseOrTimer 加入threadmap时抛出异常：{}", e.getMessage());
		       thread.dispose();
		       return;
	     }
	     //Timer timer = new Timer();
	    // ThreadTask task = new ThreadTask(thread);
	    // thread.setTimer(timer);
	    // thread.setTask(task);
	     if(thread.getTable().getBoard_state()<3)
	     {
	    	 thread.setIsout(true);
	 	     thread.dispose();
	     }else{
	    	 thread.waitReConnection();
	     }
	    
	   }
 }
